/**
 * Created by admin on 2018/7/18.
 */
const images = require('images');
const fs = require('fs');
const eachLimit = require('async/eachLimit');
const path = require('path');
const logUtil = require('../utils/log_util');
/**
 * 等比例缩放
 * ccp 20180719
 * @param maxSize 最大尺寸
 */
// images.prototype.zoom = function (maxSize) {
//   const size = this.size();
//   let height = size.height;
//   let width = size.width;
//   if (height >= width) {
//     if (height > maxSize) {
//       width = maxSize * width / height;
//       height = maxSize;
//     }
//   } else if (width > maxSize) {
//     height = maxSize * height / width;
//     width = maxSize;
//   }
//   this.width(width).height(height);
// };


const compressImage = dataPath => new Promise((res, rej) => {
  fs.readdir(dataPath, (err, files) => {
    if (err) {
      console.log(err);
      rej(err);
    }
    // 异步，一次执行10个
    eachLimit(files, 10, (filename, callback) => {
      const filePath = path.join(dataPath, filename);
      try {
        images(filePath)                   // Load image from file
          .zoom(200)                         // Geometric scaling the image to 400 pixels width
          // 等比缩放图像到400像素宽
          // .draw(images('logo.png'), 10, 10)   // Drawn logo at coordinates (10,10)
          // 在(10,10)处绘制Logo
          .save(`E:\\outImage\\${filename}`, {
            quality: 80
          });
        logUtil.info(`成功了!${filename}`);
        fs.unlink(filePath, (err) => {
          if (err) logUtil.error(err);
          setImmediate(callback);
        });
      } catch (err) {
        logUtil.error(err);
        logUtil.error(`出错了!${filename}`);
        setImmediate(callback);
      }
    }, ((err1) => {
      if (err1) { console.log(err1); rej(err1); } else { res(); }
    }));
  });
});


/**
 * 批量等比例压缩图片
 * @param ctx
 * @returns {Promise.<void>}
 */
exports.batchCompressImage = async (dataPath) => {
  await compressImage(dataPath);
};

